/********************************************************************************
* @File name: joystick.c
* @Author: Loganx
* @Gitee: https://gitee.com/loganxiang/lgxsmartcar
* @Version: 1.0(2025-10-09)
* @Description: STC32H单片机遥杆
********************************************************************************
* 本软件使用了STC的STC32G官方库
********************************************************************************/
#include "joystick.h"

uint16 joys_xraw,joys_yraw;
uint8 joyslockup,joyslockdown,joyslockleft,joyslockright;
uint8 joysig_timeout;

uint8 JoysX,JoysY;			//0 - 16
uint8 JoySigUp,JoySigDown,JoySigLeft,JoySigRight;

void JoystickInit(void){
	GPIO_InitTypeDef gpio;
	ADC_InitTypeDef adc;
	
	gpio.Pin = GPIO_Pin_0|GPIO_Pin_6;
	gpio.Mode = GPIO_HighZ;
	
	GPIO_Inilize(GPIO_P1,&gpio);
	
	adc.ADC_SMPduty = 31;
	adc.ADC_CsSetup = 0;
	adc.ADC_CsHold = 1;
	adc.ADC_Speed =  ADC_SPEED_2X16T;
	adc.ADC_AdjResult = ADC_RIGHT_JUSTIFIED;
	
	ADC_Inilize(&adc);
	ADC_PowerControl(ENABLE);
	
	NVIC_ADC_Init(DISABLE,Priority_0);
}

//joystick systick callback(100ms)
//get adc result
//if result out of signal threshold, set signal and signal timeout
//timeout reset all signal
void SystickCallbackJoys(void){
	joys_xraw = Get_ADCResult(0);
	joys_yraw = Get_ADCResult(6);
	
	JoysX = joys_xraw >> 8;
	JoysY = joys_yraw >> 8;
	
	if(JoysX > JOYSTICK_LEFT && JoysY > JOYSTICK_DOWN && JoysY < JOYSTICK_UP && joyslockleft)
	{
		JoySigLeft = TRUE;
		joyslockleft = FALSE;
		joysig_timeout = JOYSIG_TIMEOUT;
	}
	if(JoysX < JOYSTICK_RIGHT && JoysY > JOYSTICK_DOWN && JoysY < JOYSTICK_UP && joyslockright)
	{
		JoySigRight = TRUE;
		joyslockright = FALSE;
		joysig_timeout = JOYSIG_TIMEOUT;
	}
	if(JoysY > JOYSTICK_UP && JoysX < JOYSTICK_LEFT && JoysX > JOYSTICK_RIGHT && joyslockup)
	{
		JoySigUp = TRUE;
		joyslockup = FALSE;
		joysig_timeout = JOYSIG_TIMEOUT;
	}
	if(JoysY < JOYSTICK_DOWN && JoysX < JOYSTICK_LEFT && JoysX > JOYSTICK_RIGHT && joyslockdown)
	{
		JoySigDown = TRUE;
		joyslockdown = FALSE;
		joysig_timeout = JOYSIG_TIMEOUT;
	}
	
	if(12 < JoysX < 8)
		joyslockleft = joyslockright = TRUE;
	if(12 < JoysX < 8)
		joyslockup = joyslockdown = TRUE;
	
	if(joysig_timeout < 1)
	{
		JoySigUp = FALSE;
		JoySigDown = FALSE;
		JoySigLeft = FALSE;
		JoySigRight = FALSE;
	}
	else
		joysig_timeout--;
}
